package com.event.core.aspect;

import com.event.common.annotation.RepoSwitch;
import com.event.core.properties.AnnotationEventProperties;
import com.event.core.util.RepoSwitchContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @Description 开关切面
 * @Author Bing
 * @Date 2024/10/29 10:25
 */
@Slf4j
@Aspect
@Component
@Order(888)
@ConditionalOnBean(AnnotationEventProperties.class)
public class RepoSwitchAspect {

    @Pointcut("@annotation(com.event.common.annotation.RepoSwitch)")//切入点描述
    public void repoSwitch() {
    }

    @Around("repoSwitch()")
    public Object  around(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            RepoSwitch repoSwitch = method.getAnnotation(RepoSwitch.class);
            if(Objects.nonNull(repoSwitch)){
                RepoSwitchContext.set(repoSwitch.value());
            }
        }catch (Exception e){
            log.warn("repoSwitch around error", e);
        }
        try {
            return joinPoint.proceed();
        }finally {
            RepoSwitchContext.remove();
        }
    }
}